<template>
	<view class="wrap">
		<xk-header title="会议室预约"></xk-header>
		<view class="title-wrap">
			<view class="title">{{name}}</view>
			<!-- <view class="num-wrap">{{peopleNum}}人工位</view> -->
		</view>
		<dateSelect v-model="nowDate" style="margin-top: 40rpx;"></dateSelect>
		<view class="color-list-wrap">
			<view v-for="(item,i) in colorArr" :key="i" class="color-item">
				<view class="color-wrap" :style="{'backgroundColor': item.color}"></view>
				<text>{{item.name}}</text>
			</view>
		</view>
		<view class="info-wrap">
			<view class="info-item">
				<view class="info=title">小时预定</view>
				<view class="info-main">
					<view class="choose-hour-wrap">
						<view v-for="(item,i) in timeArr" :key="i">
							<view class="choose-hour-item" v-if="i+1 !== timeArr.length">
								<view class="line" v-if="i % 4 === 0">
									<view class="time">{{item.timeStr}}</view>
								</view>
								<view class="hour-item"
									:class="{'hour-item-active' : hourIndexArr.includes(i), 'hour-item-one-hour': minTime === 1}"
									@click="selectHourHandle(item,1,i,item.hourType1)"
									:style="{'backgroundColor': colorArr[item.hourType1].color}"></view>
								<view class="hour-item"
									:class="{'hour-item-active' : hourIndexArr.includes(i+timeArr.length), 'hour-item-one-hour': minTime === 1}"
									@click="selectHourHandle(item,2,i+timeArr.length,item.hourType2)"
									:style="{'backgroundColor': colorArr[item.hourType2].color}"></view>
								<view class="line" :class="{'one-hour-line': minTime === 1}">
									<view class="time">{{timeArr[i+1].timeStr}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="info-item">
				<view class="info-title">预约时间</view>
				<view class="info-main">
					<view class="nowtime-wrap">
						<view class="time-content">{{orderTime}}</view>
						<!-- <view class="price-content">合计<text class="price">{{totalPrices}}</text>元</view> -->
					</view>
					<view class="nowtime-wrap" v-if="meetingFreeHours">
						<view class="time-content">有{{meetingFreeHours}}小时可抵扣</view>
						<view class="price-content">已抵扣<text class="price">{{discounted}}</text>小时</view>
					</view>
				</view>
			</view>
			<view class="info-item" v-if="facList.length">
				<view class="info-title flex-row-between-center" style="width: 100%;">
					<view>配套设施</view>
					<u-checkbox-group v-model="facAllSelect" shape="circle" @change="selectAll">
						<u-checkbox :name="true" label="全选"></u-checkbox>
					</u-checkbox-group>
				</view>
				<view class="info-main">
					<view class="device-wrap">
						<view class="device-item" v-for="(item,i) in facList" :key="i" @click="facSelect(item)"
							:class="{'device-item-active': facIds.includes(item.data_text)}">
							<!-- <view>{{`${item.facilities_type} ${item.facilities_count}${item.unit}`}}</view> -->
							<view class="">
								{{item.data_text}}
							</view>
							<view class="select-icon">
								<u-icon name="checkmark-circle-fill" color="#3C9CFF"
									v-if="facIds.includes(item.data_text)"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 150rpx;"></view>
		<view class="bottom-bar-wrap">
			<view class="left-wrap">
				<view>已预约<text class="price">{{hourArr.length}}</text>个时间段</view>
				<!-- <view class="favour" v-if="remainTime">
					共有<text class="favour-hour">{{remainTime}}</text>个小时可抵扣
				</view>
				<view class="unfavour" v-else>
					暂无优惠时长抵扣
				</view> -->
			</view>
			<view>
				<u-button :disabled="!hourArr.length" :customStyle="sumbitButtonStyle" @click="sumbit">提交订单</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from './api.js'
	import moment from 'moment'
	export default {
		data() {
			return {
				id: '',
				price: 0,
				firstTime: '',
				lastTime: '',
				name: '',
				peopleNum: '',
				facList: [],
				facIds: [],
				facAllSelect: [],
				timeArr: [],
				hourIndexArr: [],
				hourArr: [],
				nowDate: '',
				meetingFreeHours: 0,
				prices: 0,
				discounted: 0,
				remainTime: 0,
				minTime: 0.5,
				totalPrices: 0,
				needPay: false,
				os: 'android',
				overEndTime: '',
				endTime: 24,
				startTime: 0,
				colorArr: [{
						color: '#EFEFEF',
						name: '可预约'
					},
					{
						color: '#CCCCCC',
						name: '不可预约'
					},
					{
						color: '#F85A5F',
						name: '已预约'
					},
					{
						color: '#FBAE00',
						name: '已选中'
					},
				],
				sumbitButtonStyle: {
					'height': '120rpx',
					'width': '320rpx',
					'background-color': '#CE3527',
					'color': '#fff',
					'font-size': '40rpx'
				}
			};
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id;
				this.name = options.name;
				this.peopleNum = options.num;
				//获取详情
				this.getDetail(this.id);
				uni.getSystemInfo({
					success: (res) => {
						this.os = res.osName;
						if (this.os !== 'ios') this.nowDate = moment().format('YYYY-MM-DD');
						else this.nowDate = moment().format('YYYY/MM/DD');
					}
				})
			}
			if (options.endTime) {
				this.overEndTime = options.endTime;
			}
		},
		watch: {
			nowDate(val) {
				this.calcTimeArr(this.startTime, this.endTime);
				this.getOrderedTime(this.id, val.replace(/\//g, '-'));
				this.hourArr = [];
				this.hourIndexArr = [];
			},
			facIds(val) {
				if (val.length != this.facList.length) this.facAllSelect = []
				else this.facAllSelect = [true]
			},
		},
		computed: {
			orderTime() {
				let str = ''
				let arr = this.hourArr
				if (arr.length) {
					const endTimeIsFirstHour = arr[arr.length - 1].hour === 1
					this.firstTime = `${arr[0].time}:${arr[0].hour === 1 ? '00' : '30'}`
					this.lastTime =
						`${endTimeIsFirstHour ? arr[arr.length-1].time : arr[arr.length-1].time+1}:${endTimeIsFirstHour ? '30' : '00'}`
					str = `${this.nowDate} ( ${this.firstTime}-${this.lastTime} ) ${arr.length * 0.5}小时`
				} else {
					str = `${this.nowDate} ( 未选择时间段 ) 0小时`
					this.firstTime = ''
					this.lastTime = ''
				}
				return str
			},
		},
		methods: {
			selectAll(e) {
				if (e[0])
					this.facIds = this.facList.map(item => item.data_text)
				else
					this.facIds = []
			},
			facSelect(fac) {
				const data_text = fac.data_text
				if (data_text) {
					if (this.facIds.includes(data_text)) this.facIds = this.facIds.filter(item => item !== data_text)
					else this.facIds.push(data_text)
				}
			},
			calcTimeArr(startTime, endTime) {
				let diff = endTime - startTime;
				if (diff <= 0) return;
				else {
					let arr = [];
					for (let i = 0; i <= diff; i++) {
						arr.push({
							time: startTime + i,
							timeStr: `${startTime + i}:00`,
							hourType1: 0,
							hourType2: 0,
							hourTimeStamp1: new Date(`${this.nowDate} ${startTime + i}:00`).getTime(),
							hourTimeStamp2: new Date(`${this.nowDate} ${startTime + i}:30`).getTime()
						});
						arr[arr.length - 1].hourTimeStamp3 = arr[arr.length - 1].hourTimeStamp2 + 1800000;
					}
					this.timeArr = arr;

					if (this.overEndTime) {
						setTimeout(() => {
							this.overTime(this.overEndTime);
						}, 600);
					}
				}
			},
			selectHourHandle(time, hour, hourIndex, type) {
				switch (this.minTime) {
					case 0.5:
						this.selectHour(time, hour, hourIndex, type);
						break;
					case 1:
						this.selectOneHour(time, hourIndex);
						break;
				}
			},
			selectHour(time, hour, hourIndex, type) {
				if (type !== 0) return;
				console.log(this.hourIndexArr.includes(hourIndex));
				if (this.hourIndexArr.includes(hourIndex)) {
					const length = this.timeArr.length;
					if (hourIndex === this.hourArr[0].hourIndex) {
						// 点最开始的时间段触发，不会消除大于这个时间的时间段
						this.hourIndexArr = this.hourIndexArr.filter(item => item !== hourIndex);
						this.hourArr = this.hourArr.filter(item => item.hourIndex !== hourIndex);
					} else if (hourIndex >= length) {
						// 点小时后半段触发，消除大于这个时间的时间段
						this.hourIndexArr = this.hourIndexArr.filter(item => (item !== hourIndex && item === hourIndex %
							length) || item % length < hourIndex % length);
						this.hourArr = this.hourArr.filter(item => (item.hourIndex !== hourIndex && item.hourIndex ===
							hourIndex % length) || item.hourIndex % length < hourIndex % length);
					} else {
						// 点小时前半段触发，消除大于这个时间的时间段
						this.hourIndexArr = this.hourIndexArr.filter(item => item % length < hourIndex);
						this.hourArr = this.hourArr.filter(item => item.hourIndex % length < hourIndex);
					}
				} else {
					console.log(this.hourArr.length);
					if (this.hourArr.length && !this.isConsecutive(hourIndex)) return;
					this.hourIndexArr.push(hourIndex);
					this.hourArr.push({
						hourIndex,
						...time,
						hour
					});
					this.hourArr.sort((a, b) => {
						if (a.time < b.time) return -1;
						else return 1;
					});
					// 确保0位是第一个选择的时间段
					if (this.hourArr.length > 1) {
						if (this.hourArr[0].hourIndex % this.timeArr.length === this.hourArr[1].hourIndex % this.timeArr
							.length) {
							if (this.hourArr[0].hourIndex > this.hourArr[1].hourIndex) {
								let t = this.hourArr[0];
								this.hourArr[0] = this.hourArr[1];
								this.hourArr[1] = t;
							}
						}
					}
				}
			},
			selectOneHour(time, hourIndex) {
				const length = this.timeArr.length;
				if (!this.hourArr.length) {
					this.selectHour(time, 1, hourIndex % length, time.hourType1);
					this.selectHour(time, 2, hourIndex % length + length, time.hourType2);
				} else {
					if (hourIndex >= length) {
						if (this.isConsecutive(hourIndex)) {
							this.selectHour(time, 2, hourIndex % length + length, time.hourType2);
							this.selectHour(time, 1, hourIndex % length, time.hourType1);
						} else {
							this.selectHour(time, 1, hourIndex % length, time.hourType1);
							this.selectHour(time, 2, hourIndex % length + length, time.hourType2);
						}
					} else {
						if (this.isConsecutive(hourIndex)) {
							this.selectHour(time, 1, hourIndex % length, time.hourType1);
							this.selectHour(time, 2, hourIndex % length + length, time.hourType2);
						} else {
							this.selectHour(time, 2, hourIndex % length + length, time.hourType2);
							this.selectHour(time, 1, hourIndex % length, time.hourType1);
						}
					}
				}
			},
			getOrderedTime(meetingRoomId, curdate) {
				request.getOrderedTime({
					meetingRoomId,
					curdate
				}).then(async (res) => {
					const nowTime = new Date().getTime()
					// if(!this.minTime) await this.getDetail(meetingRoomId)

					res.forEach(item => {
						const startTime = new Date(item.startTime).getTime()
						const endTime = new Date(item.endTime).getTime()

						this.timeArr.forEach(timeItem => {
							//超过时间不可预约
							if (this.minTime === 1) {
								if (timeItem.hourTimeStamp3 < nowTime) {
									timeItem.hourType1 = 1
									timeItem.hourType2 = 1
								}
							} else {
								if (timeItem.hourTimeStamp2 < nowTime && timeItem.hourType1 ===
									0)
									timeItem.hourType1 = 1
								if (timeItem.hourTimeStamp3 < nowTime && timeItem.hourType2 ===
									0)
									timeItem.hourType2 = 1
							}

							if (timeItem.hourTimeStamp1 >= startTime && timeItem
								.hourTimeStamp1 < endTime)
								timeItem.hourType1 = 2
							if (timeItem.hourTimeStamp2 >= startTime && timeItem
								.hourTimeStamp2 < endTime)
								timeItem.hourType2 = 2
						})
					})
					if (!res.length) {
						this.timeArr.forEach(timeItem => {
							//超过时间不可预约
							if (this.minTime === 1) {
								if (timeItem.hourTimeStamp3 < nowTime) {
									timeItem.hourType1 = 1
									timeItem.hourType2 = 1
								}
							} else {
								if (timeItem.hourTimeStamp2 < nowTime)
									timeItem.hourType1 = 1
								if (timeItem.hourTimeStamp3 < nowTime)
									timeItem.hourType2 = 1
							}
						})
					}
				})
			},
			overTime(endTime) {
				if (this.os === 'ios') endTime = endTime.replace(/-/g, '/');

				const hour = moment(endTime).hour();
				const minute = moment(endTime).minute();

				const time = this.timeArr.find((item) => item.time == hour);

				if (time) {
					if (minute) {
						this.selectHourHandle(time, 2, hour + this.timeArr.length, time.hourType2);
					} else {
						this.selectHourHandle(time, 1, hour, time.hourType1);
					}
				}
			},
			getDetail(meetingRoomId) {
				request.getMeetingRoomDetail({
					meetingRoomId
				}).then((data) => {
					this.price = data.price;
					this.minTime = 0.5;
					this.facList = data.roomConfigurations
				}).catch(e => {
					console.error(e);
				});
			},
			sumbit() {
				if (!this.firstTime || !this.lastTime) {
					uni.$u.toast('请选择时间');
					return;
				}
				const data = {
					meetingRoomId: this.id,
					startTime: `${this.nowDate} ${this.firstTime}`,
					endTime: `${this.nowDate} ${this.lastTime}`,
					configuration: this.facList.filter(item => this.facIds.includes(item.data_text)).map(item =>
						item.data_text).join(';')
				};
				if (this.os === 'ios') {
					data.startTime = data.startTime.replace(/\//g, '-');
					data.endTime = data.endTime.replace(/\//g, '-');
				}
				uni.showLoading({
					title: '提交中'
				});
				request.orderActivitySite(data).then(async (res) => {
					uni.hideLoading();
					uni.redirectTo({
						url: 'orderSuccess'
					});
				}).catch(e => {
					console.log(e);
					// if (e.errMsg.includes('fail cancel')) {
					//   setTimeout(() => {
					//     uni.redirectTo({
					//       url: '/pages/bus/appointment/myAppointment'
					//     });
					//   }, 500);
					// }
				});
			},
			isConsecutive(hourIndex) {
				let flag = false;
				const hourArrLength = this.hourArr.length;
				if (hourArrLength) {
					const length = this.timeArr.length;
					if (hourIndex >= length) {
						//检查最后一位
						if (this.hourArr[hourArrLength - 1].hourIndex < length) {
							if (this.hourArr[hourArrLength - 1].hourIndex === hourIndex % length) flag = true;
						}
						//检查第一位
						if (this.hourArr[0].hourIndex < length) {
							if (this.hourArr[0].hourIndex - 1 === hourIndex % length) flag = true;
						}
					} else {
						if (this.hourArr[hourArrLength - 1].hourIndex >= length) {
							if (this.hourArr[hourArrLength - 1].hourIndex % length + 1 === hourIndex) flag = true;
						}
						if (this.hourArr[0].hourIndex >= length) {
							if (this.hourArr[0].hourIndex % length === hourIndex % length) flag = true;
						}
					}
				}
				return flag;
			},
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 34rpx;
		display: flex;
		flex-direction: column;
		gap: 26rpx;

		.title-wrap {
			display: flex;
			align-items: center;
			gap: 28rpx;

			.title {
				color: #101010;
				font-size: 36rpx;
			}

			.num-wrap {
				font-size: 28rpx;
				background-color: #fbf6ef;
				border: 1px solid #E8E6E4;
				padding: 6rpx 10rpx;
				border-radius: 10rpx;
			}
		}

		.color-list-wrap {
			display: flex;
			gap: 30rpx;
			font-size: 26rpx;

			.color-wrap {
				width: 34rpx;
				height: 34rpx;
				border-radius: 6rpx;
			}

			.color-item {
				display: flex;
				align-items: center;
				gap: 6rpx;
			}
		}

		.nowtime-wrap {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 26rpx;

			.time-content {
				font-size: 26rpx;
				color: grey;
			}

			.price-content {
				.price {
					font-size: 36rpx;
					color: #FBAE00;
				}
			}
		}

		.device-wrap {
			display: grid;
			align-items: center;
			grid-template-columns: repeat(4, 22%);
			grid-gap: 20rpx;

			.device-item {
				position: relative;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 22rpx;
				text-align: center;
				border: 1px solid #bbb;
				border-radius: 20rpx;
				height: 86rpx;
			}

			.device-item-active {
				border: 1px solid #3C9CFF;
			}

			.select-icon {
				position: absolute;
				right: 0rpx;
				bottom: 0rpx;
			}
		}

		.info-wrap {
			.info-item {
				.info-title {
					color: #101010;
					font-size: 28rpx;
				}

				.info-main {
					margin-top: 16rpx;
				}
			}
		}
	}

	.bottom-bar-wrap {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 140rpx;
		padding: 16rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border: 1px solid rgba(167, 167, 167, 1);
		background-color: white;

		.left-wrap {
			color: #101010;

			.price {
				font-size: 36rpx;
				color: #FBAE00;
			}

			.favour {
				font-size: 24rpx;
				color: #CE3527;

				&-hour {
					font-size: 30rpx;
					font-weight: bold;
					color: red;
				}
			}

			.unfavour {
				font-size: 24rpx;
				color: #a7a7a7;
			}
		}

		.button-wrap {}
	}

	.choose-hour-wrap {
		display: flex;
		flex-wrap: wrap;
		margin-top: 30rpx;

		.choose-hour-item {
			display: flex;
			align-items: flex-end;
			margin-bottom: 50rpx;

			.hour-item {
				border-right: 1px solid #E6E6E6;
				border-left: 1px solid #E6E6E6;
				background-color: #EFEFEF;
				height: 80rpx;
				width: 80rpx;
			}

			.hour-item-active {
				background-color: #FBAE00 !important;
			}

			.hour-item-one-hour {
				border: none;
			}
		}

		.line {
			height: 90rpx;
			width: 1px;
			background-color: #D4D4D4;
			position: relative;

			.time {
				position: absolute;
				top: -28rpx;
				left: -28rpx;
				font-size: 22rpx;
				color: #101010;
				height: 30rpx;
				width: 60rpx;
				text-align: center;
			}
		}

		.one-hour-line {
			margin: 0 2rpx;
		}
	}
</style>